import requests
import time
import os
import json
from datetime import datetime
# CRM 教师 ID
teacherId = ''
# CRM 课程树 ID
courseTreeTemplateIds = [4233]
# OJ 用户名
oj_user_id = ''
# OJ 密码
oj_password = ''



token = ""
com_headers = {}

urls = ""


def getAllHomeworkId(text):
    jsonData = json.loads(text)
    res = []
    for now in jsonData['data'][0]['data']:
        print(now['id'], now['courseLevel'], now['unitSequence'], now['unitName'], len(
            now['homeworkIdList']), "份", now['homeworkIdList'])
        res = res + now['homeworkIdList']
        for nowid in now['homeworkIdList']:
            levelDict[nowid] = (int(now['courseLevel']) - 1) * \
                               7 + int(now['unitSequence'])
    return res


def getHomework(text):
    res = {}
    jsonData = json.loads(text)
    now = jsonData['data']['data'][0]
    res['id'] = now['id']
    res['className'] = now['className']
    res['courseName'] = levelDict[int(now['id'])]
    res['userName'] = now['userName']
    res['url'] = now['url']
    res['file_name'] = str(res['courseName']) + "_" + res['userName']
    print(res['id'], res['className'], res['file_name'], now['url'])
    return res


def getCode(url):
    url = "https:" + url
    r = requests.get(url, headers=com_headers)
    return r.text


# 获取作业份数
allHomeworkId = []
levelDict = {}
for url in urls:
    r = requests.get(url, headers=com_headers)
    allHomeworkId = allHomeworkId + getAllHomeworkId(r.text)

# 获取作业链接
urls = ['https://crm.hetao101.com/crm-homework/v2/comment/homework?idList=' +
        str(nowid) for nowid in allHomeworkId]
allHomework = []
for url in urls:
    r = requests.get(url, headers=com_headers)
    allHomework.append(getHomework(r.text))



def pushcode(token1,crmid,temp_data1):
    global token
    global com_headers
    st=str(datetime.now())
    token=token1
    #token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJvbGRfc3RhZmZfdW5pZmllZF9hdXRoX3Rva2VuOndlYjptaWx1IiwiY3JlYXRlZCI6MTczMDAwNTQ1NTU5NSwibmlja25hbWUiOiLpuovpub_ogIHluIgiLCJpZCI6MzAwMDc3OTYsImV4cCI6MTczMDYxMDI1NSwic3RhZmZJZCI6MTgwMTQsInVzZXJuYW1lIjoibWlsdSJ9.Ssiybg5AtCSFzJ-NF9q7LpPs3KUpzAMfkyU6ITcKEnQCICO2Zqy1yALVxJ6Fn-01VWudErASzTCM0R5rQ5sj5g"

    com_headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36",
        "cookie": "tokenCrm=" + token
    }
    # CRM 教师 ID
    teacherId = crmid
    # CRM 课程树 ID
    courseTreeTemplateIds = [4233]
    # OJ 用户名
    # oj_user_id = temp_data["user_id"]
    # # OJ 密码
    # oj_password = temp_data["password"]
    oj_pid =[0,                     #准备课
    1318,1323,1317,1324,0,0,0,  # L1
    1325,0,0,0,0,0,0,            #L2 缺习题课
    0,0,0,0,0,0,0,      #L3
    0,0,0,0,0,0,0,            #L4
    0,0,0,0,0,0,0,            #L5 缺习题课
    0,0,0,0,0,0,0,         #L6 缺习题课
    0,0,0,0,0,0,0,            #L7
    0,0,0,0,0,0,0,         #L8

    1278,1279,1280,1281,1282,1283,0,#L9
    1284,1285,1286,0,1287,1288,0,   #L10   10-4习题课暂无题目
    1289,1290,1291,1309,1310,0,0,   #L11 11-6习题课暂无题目
    1311,1312,1313,1314,0,0,0,      #L12 12-5习题课暂无题目

    0,0,0,0,0,0,0,                  #L13 缺
    0,0,0,0,0,0,0,                  #L14 缺
    0,0,0,0,0,0,0,                  #L15 缺
    0,0,0,0,0,0,0,                  #L16 缺

    1307,1308,1315,0,0,0,0,            #L17 后续暂无
            ]
    urls = ['https://crm.hetao101.com/crm-homework/v2/comment/class/courseInfo?teacherId=' +
            str(teacherId) + '&dataType=0&courseTreeTemplateId=' + str(cttid) for cttid in courseTreeTemplateIds]

    # 获取作业份数
    allHomeworkId = []
    levelDict = {}
    for url in urls:
        r = requests.get(url, headers=com_headers)
        allHomeworkId = allHomeworkId + getAllHomeworkId(r.text)

    # 获取作业链接
    urls = ['https://crm.hetao101.com/crm-homework/v2/comment/homework?idList=' +
            str(nowid) for nowid in allHomeworkId]
    allHomework = []
    for url in urls:
        r = requests.get(url, headers=com_headers)
        allHomework.append(getHomework(r.text))

    oj_login_url = "http://82.157.207.59/login.php"
    temp_data = temp_data1
    req = requests.post(oj_login_url, headers=com_headers, data=temp_data)
    req_cookie = requests.utils.dict_from_cookiejar(req.cookies)
    oj_cookie = ''
    for key in req_cookie:
        oj_cookie += '{0}={1};'.format(key, req_cookie[key])
    oj_submit_url = "http://82.157.207.59/submit.php"

    oj_headers = {
        'Cookie': oj_cookie,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67'
    }

    for homework in allHomework:
        if homework['courseName'] < len(oj_pid):
            oj_data = {
                "id": str(oj_pid[homework['courseName']]),
                "language": "1",
                "source": "//L" + str((homework['courseName'] - 1) // 7 + 1) + "-" + str(
                    (homework['courseName'] - 1) % 7 + 1) + " " + homework['userName'] + "\n" + getCode(
                    homework['url']),
                "userName": "L" + str((homework['courseName'] - 1) // 7 + 1) + "-" + str(
                    (homework['courseName'] - 1) % 7 + 1),
                "className": homework['userName']
            }
            req = requests.post(oj_submit_url, headers=oj_headers, data=oj_data)
            print(homework['file_name'], req)
            time.sleep(0.8)
    print("-----提交完成-----")
    return st
    #os.system("pause")
